package com.example.daily.ui.foodrecord

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.daily.data.entity.FoodRecord
import com.example.daily.ui.navigation.Screen
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.util.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FoodRecordScreen(
    viewModel: FoodRecordViewModel = hiltViewModel(),
    navController: NavController
) {
    val uiState by viewModel.uiState.collectAsState()
    var showAddDialog by remember { mutableStateOf(false) }

    // 处理从食物识别页面返回的结果
    LaunchedEffect(navController) {
        val savedStateHandle = navController.currentBackStackEntry?.savedStateHandle
        val foodName = savedStateHandle?.get<String>("food_name")
        val foodCalories = savedStateHandle?.get<Int>("food_calories")
        
        if (foodName != null && foodCalories != null) {
            viewModel.addFoodRecord(foodName, foodCalories, LocalDateTime.now())
            // 清除已处理的数据
            savedStateHandle.remove<String>("food_name")
            savedStateHandle.remove<Int>("food_calories")
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("今日饮食记录") },
                actions = {
                    Text("总热量: ${uiState.totalCalories} 卡路里")
                }
            )
        },
        floatingActionButton = {
            Column {
                SmallFloatingActionButton(
                    onClick = { showAddDialog = true },
                    modifier = Modifier.padding(bottom = 8.dp)
                ) {
                    Icon(Icons.Default.Add, contentDescription = "手动添加")
                }
                
                FloatingActionButton(
                    onClick = {
                        navController.navigate(Screen.FoodRecognition.route)
                    }
                ) {
                    Icon(Icons.Default.PhotoCamera, contentDescription = "识别添加")
                }
            }
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            if (uiState.isLoading) {
                CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
            } else if (uiState.error != null) {
                Text(
                    text = "错误: ${uiState.error}",
                    color = MaterialTheme.colorScheme.error,
                    modifier = Modifier.align(Alignment.Center)
                )
            } else if (uiState.foodRecords.isEmpty()) {
                Text(
                    text = "今天还没有记录饮食",
                    modifier = Modifier.align(Alignment.Center)
                )
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp)
                ) {
                    items(uiState.foodRecords) { record ->
                        FoodRecordItem(
                            foodRecord = record,
                            onDelete = { viewModel.deleteFoodRecord(record) }
                        )
                    }
                }
            }
        }

        if (showAddDialog) {
            AddFoodRecordDialog(
                onDismiss = { showAddDialog = false },
                onConfirm = { name, calories ->
                    viewModel.addFoodRecord(name, calories, LocalDateTime.now())
                    showAddDialog = false
                }
            )
        }
    }
}

@Composable
fun FoodRecordItem(
    foodRecord: FoodRecord,
    onDelete: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = foodRecord.foodName,
                    style = MaterialTheme.typography.titleMedium
                )
                Text(
                    text = "${foodRecord.calories} 卡路里",
                    style = MaterialTheme.typography.bodyMedium
                )
                Text(
                    text = SimpleDateFormat("HH:mm", Locale.getDefault())
                        .apply { timeZone = TimeZone.getDefault() }
                        .format(Date(foodRecord.recordDate)),
                    style = MaterialTheme.typography.bodySmall
                )
            }
            IconButton(onClick = onDelete) {
                Icon(Icons.Default.Delete, contentDescription = "删除")
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddFoodRecordDialog(
    onDismiss: () -> Unit,
    onConfirm: (String, Int) -> Unit
) {
    var foodName by remember { mutableStateOf("") }
    var calories by remember { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("添加食物记录") },
        text = {
            Column {
                OutlinedTextField(
                    value = foodName,
                    onValueChange = { foodName = it },
                    label = { Text("食物名称") }
                )
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedTextField(
                    value = calories,
                    onValueChange = { calories = it },
                    label = { Text("卡路里") }
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    calories.toIntOrNull()?.let { cal ->
                        onConfirm(foodName, cal)
                    }
                }
            ) {
                Text("确定")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
} 